﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.WriteAPI.Applications.Commands.DangerousCommands;
using MediatR;

namespace B.S.BaseData.WriteAPI.Applications.CommandHandlers.DangerousCommandHandlers
{
    public class AddDangerousCommandHandler:IRequestHandler<AddDangerousCommand,ApiResult<int>>
    {
        IBaseRepository<Dangerous> dangerousrepository;
        ILogger<AddDangerousCommandHandler> logger;
        IMapper mapper;

        public AddDangerousCommandHandler(IBaseRepository<Dangerous> dangerousrepository, ILogger<AddDangerousCommandHandler> logger, IMapper mapper)
        {
            this.dangerousrepository = dangerousrepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddDangerousCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ApiResult<int>();

                var data = mapper.Map<Dangerous>(request.data);
                var res = await dangerousrepository.AddAsync(data);
                if(res>0)
                {
                    result.data = res;
                    result.success(res);
                }

                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("事故添加出错" + ex.Message);
                throw;
            }
        }
    }
}
